#!/usr/bin/perl

use Getopt::Long;

## Command executing program in remote host
#
#Options
#  --help : 
#    print usage
#  --file <Remote host list>:
#  --igfile <ignore Host list file>:
#  --start <Start Line Num>:
#  --end <End line Num>:
#    conecting Remote host file's (line 'start' to 'end') hosts
#  --command <'execute command'>
#    execute command in remote hosts
#  --user
#    set remote hosts user name
#
#Autor yosilove @ Yamada Lab
#Date 2009/12/26
#

my $showHelp=0;

my $user='';#remote host user
my $filename = 'remote_hosts.lst';#Hostname List
my $igfilename = 'remote_hosts_ignore.lst';
my $start = 1;#Start Line
my $end = 120;#End Line
my $command = 'hostname';#execute command


GetOptions('file=s' => \$filename,'igfile=s' => \$igfilename,'start=i' => \$start, 'end=i' => \$end,
	 'command=s' => \$command, 'user=s' => \$user, 'help' => \$showHelp);

##
## Show Usage
##	if set help option
##
if($showHelp == 1){
  print "Usage : $__FILE__ [hcfise] \n";
  print "\t --help (or -h)\t:show this usage\n";

  print "\t --command (or -c) <'execute command'>\t: define execute command in remote hosts (default:$command)\n";
  print "\t --file (or -f) <Host list file>\t: define Host list file (default:$filename)\n";
  print "\t --igfile (or -i) <ignore Host list file>\t: define Ignore Host list file (default:$igfilename)\n";
  print "\t --start (or -s) <Start Line num>\t: define start line number (default:$start)\n";
  print "\t --end (or -e) <End Line num>\t: define end line number (default:$end)\n";

  print "\t --user (or -u) <User name>\t: set remote user name (default:NULL)\n";

  exit;
}

##
##print infomations
##
print "Read, $filename. Line $start to $end\n";
if($user eq ''){
  print "execute [$command] in remote hosts\n\n";
}else{
  print "execute $command by $user in remote hosts\n\n";
}


##
## Executing command in remote hosts ##
##
print "\n++++ Start ++++\n";


%remotes = readLst($filename,$start,$end);
#print %remotes, "\n";

%ignores = readLst($igfilename,0,0);
#print %ignores,"\n";

foreach $key (keys %ignores){
  delete $remotes{$key};
}
#print %remotes, "\n";

execCmd($user,$command,%remotes);

sub execCmd{
  ($user,$command,%remotes) = @_;
 
  #sorting
  @keys = sort keys %remotes;
 
  foreach $key (@keys){
    if($user eq ''){
      $exec = "ssh $key $command";
    }else{
      $exec = "ssh $user\@$key $command";
    }

    #show execution and execute
    print "\n$exec\n";
    print `$exec`;
  }
}

sub readLst {
  ($filename,$start,$end)=@_;

  open(LIST,$filename);
  my $count=0;
  my %remote_list=();

  while(<LIST>){
    $count++;
    #skipping lines
    if ($start > 0 && $end > 0){
      next if($count < $start);#skip to start line
      last if($end < $count);#end loop
    }

    chomp;#delete CR and LF code
    $remote_list{$_} = "";
  }
  close(LIST);

  return %remote_list;
}
